"""
Verification script for combined createTask + generatePptx API
Tests the two-step workflow: create task -> generate PPTX
"""
import sys
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from src.llm.aippt_app.utils.api_client import AIPPTAPIClient
import json


def test_combined_workflow():
    """Test the combined createTask + generatePptx workflow"""
    print("=" * 60)
    print("Testing Combined CreateTask + GeneratePptx Workflow")
    print("=" * 60)

    client = AIPPTAPIClient()

    # Step 1: Create Task
    print("\n[Step 1] Creating task...")
    print("-" * 60)

    task_type = 6  # Paste text content
    content = "Artificial Intelligence and Machine Learning in Modern Business"

    try:
        create_response = client.create_task(
            task_type=task_type,
            content=content
        )
        print(f"Create Task Response:")
        print(json.dumps(create_response, indent=2, ensure_ascii=False))

        if create_response.get('code') != 0:
            print(f"\nERROR: Create task failed with code {create_response.get('code')}")
            print(f"Message: {create_response.get('message')}")
            return

        task_id = create_response['data'].get('id')
        if not task_id:
            print("\nERROR: No task ID in response")
            return

        print(f"\nSUCCESS: Task created with ID: {task_id}")

    except Exception as e:
        print(f"\nERROR creating task: {str(e)}")
        return

    # Step 2: Generate PPTX
    print("\n[Step 2] Generating PPTX...")
    print("-" * 60)

    # Get a template first
    print("Getting templates to select one...")
    try:
        templates_response = client.list_templates(
            current=1,
            size=5,
            template_type=1,
            lang='zh'
        )

        if templates_response.get('code') == 0 and templates_response.get('data'):
            templates = templates_response['data']
            if templates:
                template_id = templates[0].get('id')
                print(f"Using template ID: {template_id}")
                print(f"Template name: {templates[0].get('name', 'Unknown')}")
            else:
                print("ERROR: No templates available")
                return
        else:
            print(f"ERROR: Failed to get templates")
            return

    except Exception as e:
        print(f"ERROR getting templates: {str(e)}")
        return

    # Prepare markdown content
    markdown = """# Artificial Intelligence and Machine Learning in Modern Business

## Introduction
### What is AI and ML?
- Artificial Intelligence: Simulation of human intelligence
- Machine Learning: Subset of AI that learns from data
- Deep Learning: Advanced ML using neural networks

## Business Applications
### Key Use Cases
- Customer service automation
- Predictive analytics
- Fraud detection
- Personalized recommendations

## Benefits
### Advantages for Business
- Increased efficiency
- Cost reduction
- Better decision making
- Enhanced customer experience

## Challenges
### Implementation Hurdles
- Data quality issues
- High initial investment
- Skill gap
- Ethical considerations

## Future Trends
### What's Next
- Edge AI
- Explainable AI
- AI regulation
- Democratization of AI
"""

    print("\nMarkdown content prepared:")
    print(markdown[:200] + "...")

    try:
        pptx_response = client.generate_pptx(
            task_id=task_id,
            template_id=template_id,
            markdown=markdown
        )

        print(f"\nGenerate PPTX Response:")
        print(json.dumps(pptx_response, indent=2, ensure_ascii=False))

        if pptx_response.get('code') != 0:
            print(f"\nERROR: Generate PPTX failed with code {pptx_response.get('code')}")
            print(f"Message: {pptx_response.get('message')}")
            return

        ppt_info = pptx_response.get('data', {}).get('pptInfo')
        if ppt_info:
            print(f"\nSUCCESS: PPT generated!")
            print(f"PPT ID: {ppt_info.get('id')}")
            print(f"Subject: {ppt_info.get('subject')}")
            print(f"Cover URL: {ppt_info.get('coverUrl')}")
            print(f"Template ID: {ppt_info.get('templateId')}")
        else:
            print("\nWARNING: No pptInfo in response")

    except Exception as e:
        print(f"\nERROR generating PPTX: {str(e)}")
        import traceback
        traceback.print_exc()
        return

    print("\n" + "=" * 60)
    print("Combined workflow test completed successfully!")
    print("=" * 60)


if __name__ == "__main__":
    test_combined_workflow()
